class List {
    constructor() {
        this.getDate();
        this.checkLogin();
    }
    //数据的获取
    async getDate() {
        let { data, status } = await axios.get('http://localhost:8888/goods/list')
        // console.log(data, status);
        // 循环追加到页面中
        //判断发送状态
        if (status != 200 || data.code != 1) return;
        let html = '';
        data.list.forEach(goods => {
            // console.log(goods);
            html += ` <li class="sk_goods">
            <a href="#none" onclick='List.getId(${goods.goods_id})'><img src="${goods.img_big_logo}" alt=""></a>
            <h5 class="sk_goods_title">${goods.title}</h5>
            <p class="sk_goods_price"><em>￥${goods.current_price}</em> <del>￥${goods.price}</del></p>
            <div class="sk_goods_progress">
                已售<i>${goods.sale_type}</i>
                <div class="bar">
                    <div class="bar_in"></div>
                </div>
                剩余<em>${goods.goods_number}</em>件
            </div>
            <a href="#none" class="sk_goods_buy" onclick="List.nowBuy(${goods.goods_id})">立即抢购</a>
        </li>`
        });
        //将商品数据添加到页面中
        this.$('.sk_bd ul').innerHTML = html;
    }
    //验证是否登录
    checkLogin() {
        const TOKEN = localStorage.getItem('token');
        if (!TOKEN) location.assign('./login.html');
        let userName = localStorage.getItem('userName')
        let Name = document.querySelector('.fr li');
        if (TOKEN) {
            Name.firstElementChild.innerHTML = userName;
        }
    }
    //进入详情页
    static getId(goodsId) {
        // console.log(goodsId);
        localStorage.setItem('goodsId', goodsId)
        location.href = './detail.html'
    }
    //立即抢购
    static nowBuy(goodsId) {
        //判断是否有token
        let token = localStorage.getItem('token');
        if (!token) location.href = './login.html';
        //将购买商品加入购物车
        let userId = localStorage.getItem('user_id');
        let param = `id=${userId}&goodsId=${goodsId}`;
        //商品id
        // console.log(userId, goodsId);
        // 设置编码方式
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        axios.defaults.headers.common['Authorization'] = token;
        axios.post('http://localhost:8888/cart/add', param).then(res => {
            let { status, data } = res;
            //status 200请求服务器成功   code 1 接口成功
            // 判断服务器状态
            if (status != 200) return;
            if (data.code == 0) location.href = './login.html'

            layer.confirm('是否去购物车结算', {
                btn: ['是', '继续购买'] //按钮
            }, function () {
                // layer.msg('的确很重要', { icon: 1 });
                location.href = './cart.html';
            }, function () {

            });
        });

    }

    //获取节点的方法
    $(ele) {
        let res = document.querySelectorAll(ele);
        return res.length == 1 ? res[0] : res;
    }
}
new List();